package com.rambo.xpd.base.demo;

import com.rambo.xpd.base.vo.StudentGridlb;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Create by Rambo on 2017/5/10
 * 依赖 :xmlpull inter
 * xpp3 impl
 **/
public class XmlPullDemo {

    public static void main(String[] args) throws Exception {
        XmlPullParserFactory pullParserFactory = XmlPullParserFactory.newInstance();
        XmlPullParser pullParser = pullParserFactory.newPullParser();//获取XmlPullParser的实例
        pullParser.setInput(Thread.currentThread().getContextClassLoader().getResourceAsStream("demo.xml"), "UTF-8");

        int event = pullParser.getEventType();
        List<StudentGridlb> studentGridlbList = new ArrayList<>();
        StudentGridlb studentGridlb = new StudentGridlb();

        while (event != XmlPullParser.END_DOCUMENT) {
            String nodeName = pullParser.getName();
            switch (event) {
                case XmlPullParser.START_DOCUMENT:
                    System.out.println("xmlpull 解析 xml 开始:");
                    break;
                case XmlPullParser.START_TAG:
                    if ("stu_id".equals(nodeName)) {
                        studentGridlb.setStu_id(pullParser.nextText());
                    }
                    if ("stu_name".equals(nodeName)) {
                        studentGridlb.setStu_name(pullParser.nextText());
                    }
                    if ("stu_age".equals(nodeName)) {
                        studentGridlb.setStu_age(Integer.parseInt(pullParser.nextText()));
                    }
                    if ("stu_birthday".equals(nodeName)) {
                        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                        studentGridlb.setStu_birthday(format.parse(pullParser.nextText()));
                    }
                    break;
                case XmlPullParser.END_TAG:
                    if ("studentGridlb".equals(nodeName)) {
                        studentGridlbList.add(studentGridlb);
                        studentGridlb = new StudentGridlb();
                    }
                    break;
            }
            event = pullParser.next();
        }
        System.out.println(studentGridlbList.toString());
    }
}